<template>
  <div class="operation-buttons">
    <el-button text type="primary" @click="handleDetails">详情</el-button>

    <!-- 详情弹窗 -->
    <el-dialog v-model="showDetailDialog" append-to-body title="通知详情" width="80%">
      <!-- 查询表单 -->
      <div class="qs-y-table-header" style="border: none; height: auto; width: 100%">
        <div class="header-query">
          <div>
            <el-button type="primary" @click="fetchData">刷新</el-button>
          </div>
          <el-form :inline="true" :model="detailQuery">
            <el-form-item label="接收人">
              <el-input v-model="detailQuery.userId" clearable placeholder="请输入接收人" />
            </el-form-item>
            <el-form-item label="发送状态">
              <el-select v-model="detailQuery.notifySendStatus" clearable placeholder="请选择发送状态">
                <el-option
                  v-for="[value, label] in Object.entries(statusDict.notifySendStatus)"
                  :key="value"
                  :label="label"
                  :value="value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="接收状态">
              <el-select v-model="detailQuery.notifyReceiveStatus" clearable placeholder="请选择接收状态">
                <el-option
                  v-for="[value, label] in Object.entries(statusDict.notifyReceiveStatus)"
                  :key="value"
                  :label="label"
                  :value="value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 表格 -->
      <el-table v-loading="loading" border :data="list" stripe>
        <el-table-column align="center" label="序号" width="55">
          <template #default="{ $index }">
            {{ (detailQuery.page - 1) * detailQuery.limit + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="接收人" prop="userId" />
        <el-table-column align="center" label="发送状态" prop="notifySendStatus">
          <template #default="{ row }">
            {{ statusDict.notifySendStatus[row.notifySendStatus] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="接收状态" prop="notifyReceiveStatus">
          <template #default="{ row }">
            {{ statusDict.notifyReceiveStatus[row.notifyReceiveStatus] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="通知时间" prop="notifyTime" />
        <el-table-column align="center" fixed="right" label="操作" width="120">
          <template #default="{ row }">
            <el-button text type="primary" @click="handleViewContent(row)">查看内容</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        background
        class="pagination"
        :current-page="detailQuery.page"
        :layout="layout"
        :page-size="detailQuery.limit"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-dialog>

    <!-- 通知内容查看弹窗 -->
    <el-dialog v-model="showContentDialog" append-to-body title="通知内容" width="60%">
      <div class="notification-content" v-html="selectedContent"></div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import request from '/@/utils/request'

interface Props {
  moduleApi: string
  statusDict: Record<string, Record<string, string>>
  row: any
}

interface NotificationDetail {
  id?: number
  taskId: number
  userId: string
  content: string
  notifySendStatus: '0' | '1'
  notifyReceiveStatus: '0' | '1'
  notifyTime: string
}

interface RequestResponse<T = any> {
  code: number
  result: T
  message?: string
}

const props = defineProps<Props>()

// 状态定义
const loading = ref(false)
const list = ref<NotificationDetail[]>([])
const total = ref(0)
const layout = ref('total, sizes, prev, pager, next, jumper')
const showDetailDialog = ref(false)
const showContentDialog = ref(false)
const selectedContent = ref('')

// 查询参数
const detailQuery = ref({
  page: 1,
  limit: 20,
  taskId: '',
  userId: '',
  notifySendStatus: '',
  notifyReceiveStatus: '',
})

// 获取详情数据
const fetchData = async () => {
  // 检查是否有有效的ID
  if (!props.row || !props.row.id) {
    ElMessage.error('无法获取详情：未找到有效的通知任务ID')
    return
  }

  loading.value = true
  try {
    const res = (await request({
      url: `${props.moduleApi}/show/${props.row.id}`,
      method: 'get',
      params: {
        ...detailQuery.value,
        activityId: localStorage.getItem('hongyouActId'),
      },
    })) as RequestResponse<{ rows: NotificationDetail[]; count: number }>
    if (res?.code === 0 && res?.result) {
      list.value = res.result.rows
      console.log(res.result.rows)
      console.log(res.result)
      console.log(res)

      total.value = res.result.count
    }
  } catch {
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 查看通知内容
const handleViewContent = (row: NotificationDetail) => {
  selectedContent.value = row.content
  showContentDialog.value = true
}

// 查询
const handleSearch = () => {
  detailQuery.value.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  detailQuery.value = {
    ...detailQuery.value,
    userId: '',
    notifySendStatus: '',
    notifyReceiveStatus: '',
    page: 1,
  }
  fetchData()
}

// 分页处理
const handleSizeChange = (val: number) => {
  detailQuery.value.limit = val
  detailQuery.value.page = 1
  fetchData()
}

const handleCurrentChange = (val: number) => {
  detailQuery.value.page = val
  fetchData()
}

// 查看详情
const handleDetails = () => {
  // 检查是否有有效的ID
  if (!props.row || !props.row.id) {
    ElMessage.error('无法查看详情：未找到有效的通知任务ID')
    return
  }

  detailQuery.value.taskId = props.row.id.toString()
  showDetailDialog.value = true
  fetchData()
}
</script>

<style lang="scss" scoped>
.operation-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.notification-content {
  max-height: 500px;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

.pagination {
  margin-top: 15px;
  justify-content: flex-end;
}
</style>
